<template>
  <div class="container bg-white">
    <blank
      :value="showEmpty"
      :title="empty.title"
      :message="empty.message"
      :icon="empty.icon"
    />
    <van-loading
      size="24px"
      vertical
      v-if="authenting"
    >等待微信授权结果...</van-loading>
    <van-button
      type="default"
      icon="bulb-o"
      size="small"
      v-if="debug"
      @click="showPopup"
    >DEBUG</van-button>
    <van-popup
      v-model="showDebug"
      class="debug"
      position="bottom"
      closeable
      close-icon-position="bottom-left"
      :style="{ height: '100%' }"
    >
      <h1>微信授权调试信息</h1>
      <json-viewer
        :value="debug"
        :expand-depth=5
        copyable
        sort
      />
    </van-popup>
  </div>
</template>

<script>
import qs from 'qs'
import { Loading, Button, Popup } from 'vant'
import JsonViewer from 'vue-json-viewer'
import Blank from '../../components/abnor/blank'
import Security from '@/common/security'
import { getFingerprintID } from '@/common/systeminfo'
/**
 * 微信网页授权
 */
export default {
  name: 'Auth',
  components: {
    JsonViewer,
    Blank,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Loading.name]: Loading
  },
  data () {
    return {
      showEmpty: false,
      authenting: true,
      empty: {
        title: '微信授权失败',
        message: '抱歉，当前微信授权失败...',
        icon: '/static/icons/blank_authent.png'
      },
      showDebug: false,
      webAuthData: null,
      params: null,
      token: null,
      locationData: location
    }
  },
  watch: {
    token: {
      handler (v, o) {
        if (v) {
          this.$storage.setAccessToken(v)
          this.goBack()
        }
      },
      deep: true
    }
  },
  computed: {
    wechatUriParams () {
      const url = location.search
      if (url.indexOf('?') !== -1) {
        return qs.parse(url.substr(1))
      }
      return null
    },
    debug () {
      if (
        process.env.NODE_ENV === 'development' ||
        process.env.NODE_ENV === 'production'
      ) {
        return {
          webAuthData: this.wechatUriParams,
          params: this.params,
          locationData: {
            hash: location.hash,
            host: location.host,
            hostname: location.hostname,
            href: location.href,
            origin: location.origin,
            pathname: location.pathname,
            port: location.port,
            protocol: location.protocol,
            search: location.search
          }
        }
      }
      return false
    }
  },
  created () {
    let connectId = sessionStorage.getItem('wxUserInfo')
    console.log(
      'wx---------------------------------------------------------------',
      connectId
    )

    // 如果连接中有微信返回的 code，则用此 code 调用后端接口，向微信服务器请求用户信息
    // 如果不是从微信重定向过来的，没有带着微信的 code，则直接进入首页
    if (this.wechatUriParams && this.wechatUriParams.code) {
      if (Security.getAccessToken()) {
        this.connect()
      } else {
        this.register()
      }
    } else {
      this.authenting = false
      this.showEmpty = true
      // this.$router.replace('/')
    }

    // this.params = this.wechatUriParams
    // // 如果连接中有微信返回的 code，则用此 code 调用后端接口，向微信服务器请求用户信息
    // // 如果不是从微信重定向过来的，没有带着微信的 code，则直接进入首页
    // if (this.wechatUriParams && this.wechatUriParams.code) {
    //   this.$http.base
    //     .wechatAuthorize(this.wechatUriParams.code)
    //     .then(res => {
    //       let data = res.data
    //       console.log(data)
    //       this.webAuthData = data
    //       sessionStorage.setItem('wxUserInfo', JSON.stringify(data))
    //       // localStorage.setItem('wxUserInfo', JSON.stringify(data))
    //       this.backToReturnUrl()
    //     })
    //     .catch(err => {
    //       console.log(err)
    //       this.authenting = false
    //       this.showEmpty = true
    //     })
    // } else {
    //   this.authenting = false
    //   this.showEmpty = true
    //   // this.$router.replace('/')
    // }
  },
  methods: {
    backToReturnUrl () {
      let redirectUrl = sessionStorage.getItem('wxRedirectUrl')
      console.log('redirectUrl', redirectUrl)
      // sessionStorage.removeItem('wxRedirectUrl')
      // window.location.href = window.location.origin + '/#' + redirectUrl
      // this.$router.replace(redirectUrl)
      this.authenting = false
    },
    connect () {
      this.$http.base
        .wechatAuthorize(this.wechatUriParams)
        .then(res => {
          let data = res.data
          console.log(data)
          this.webAuthData = data
          if (data.connect_id) {
            sessionStorage.setItem('wxUserInfo', data.connect_id)
          }
          // localStorage.setItem('wxUserInfo', JSON.stringify(data))
          this.backToReturnUrl()
        })
        .catch(err => {
          console.log(err)
          this.authenting = false
          this.showEmpty = true
        })
    },
    async register () {
      let systemInfo = this.$storage.get('systemInfo')
      if (!systemInfo) {
        systemInfo = await getFingerprintID()
        this.$storage.set('systemInfo', systemInfo)
      }
      let params = Security.generateSignature({
        sn: systemInfo.sn,
        os: systemInfo.os.name,
        install: this.install,
        model: systemInfo.device ? systemInfo.device.model : ''
      })

      this.params = Object.assign({}, params, this.wechatUriParams)
      this.$http.base
        .wechatAuthorize(this.wechatUriParams)
        .then(res => {
          let data = res.data
          console.log(data)
          this.webAuthData = data
          if (data.connect_id) {
            sessionStorage.setItem('wxUserInfo', data.connect_id)
          }
          // localStorage.setItem('wxUserInfo', JSON.stringify(data))
          this.backToReturnUrl()
        })
        .catch(err => {
          console.log(err)
          this.authenting = false
          this.showEmpty = true
        })

      // appid : '2018071144'
      // build : 1
      // install : 0
      // nonce : 'vSvEEcTYY7bLOTDTvMqNRsmesnf6x7ZG'
      // os : 'Windows'
      // sign : '982067fabe17369bb5b02dcb0b27f452eaf89825b6eda6f9cdfc9630da9bdc43'
      // sn : 'ad60f7cd6e2b187f56f23a543ce36ec0'
      // timestamp : '1577188469'
      this.$http.base.authorize(params).then(res => {
        this.token = res.data
      })
    },
    async onAuthent () {
      let systemInfo = this.$storage.get('systemInfo')
      if (!systemInfo) {
        systemInfo = await getFingerprintID()
        this.$storage.set('systemInfo', systemInfo)
      }
      let params = Security.generateSignature({
        sn: systemInfo.sn,
        os: systemInfo.os.name,
        install: this.install,
        model: systemInfo.device ? systemInfo.device.model : ''
      })
      this.params = Object.assign({}, params, this.wechatUriParams)
      // appid : '2018071144'
      // build : 1
      // install : 0
      // nonce : 'vSvEEcTYY7bLOTDTvMqNRsmesnf6x7ZG'
      // os : 'Windows'
      // sign : '982067fabe17369bb5b02dcb0b27f452eaf89825b6eda6f9cdfc9630da9bdc43'
      // sn : 'ad60f7cd6e2b187f56f23a543ce36ec0'
      // timestamp : '1577188469'
      this.$http.base.authorize(params).then(res => {
        this.token = res.data
      })
    },
    parseWechatUriParams () {
      const url = location.search
      if (url.indexOf('?') !== -1) {
        return qs.parse(url.substr(1))
      }
      return null
    },
    showPopup () {
      this.showDebug = true
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.van-loading {
  height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.van-popup {
  h1 {
    margin: 0;
    font-size: 14px;
    padding: 15px;
    border-bottom: 1px solid #f2f2f2;
  }
}
.van-button {
  position: fixed;
  right: 2px;
  bottom: 2px;
}
</style>
